<template>
	<view class="content" v-if="!init">
    <template v-if="record._id">
      
      <view style="height: 320px;margin-top: 250rpx" v-if="page_qrcode">
      	<!-- <l-painter ref="painter" css="background-color:#ffffff;width:250px;">
      			<l-painter-view css="background-color: red;width: 100%;text-align: center;padding-top: 8px;padding-bottom: 8px;">
      				<l-painter-text css="font-weight: bolder;display: block; padding-bottom: 5px; color: #fff; font-size: 16px;" text="支付宝红包"></l-painter-text>
      			</l-painter-view>
      			<l-painter-view css="margin-top: 20px;text-align: center;width: 100%;">
      				<l-painter-image
      					css="object-fit: cover;object-position: 50% 50%;width: 190px; height: 190px;border-radius: 6px;" 
      					:src="page_qrcode"></l-painter-image>
      			</l-painter-view>
      			<l-painter-view css="background-color: red;margin-top: 15px;width: 100%;text-align: center;padding-top: 15px;padding-bottom: 15px;">
      					<l-painter-text css="color: #fff; font-size: 14px" text="长按识别二维码领支付宝红包"></l-painter-text>
      			</l-painter-view>
      	</l-painter> -->
        <image :src="page_qrcode" mode="widthFix"></image>
      </view>
      <text style="color: #666;font-size: 24rpx;margin-top: 0rpx;">长按图片下载</text>
      <view style="display: flex;justify-content: space-evenly;width: 250px;margin-top: 80rpx">
        <!-- <button @click="downloadPoster" type="primary" style="font-size: 32rpx;">下载海报</button> -->
        <button 
        type="warn" style="font-size: 32rpx;" 
        @click="copy(`不用扫码，点击链接自动跳转支付宝领红包${indexPage}#/pages/index?id=${record._id}`)">复制红包专属页链接</button>
      </view>
      <a :href="indexPage" style="color: #666;font-size: 24rpx;margin-top: 20rpx;">返回首页</a>
    </template>
    <template v-else>
      <uni-file-picker
          style="margin-top: 30%;background-image: linear-gradient(to bottom, #fd6748, #ffd08b,#fd6748);border: 1px solid red;border-radius: 5px;"
      		:image-styles="style"
          v-model="source_qrcode"  
          file-mediatype="image"
          mode="grid"
          file-extname="png,jpg,jpeg"
          :limit="1"/>
      <text style="color: #666;font-size: 24rpx;margin-top: 20rpx;">确保是你的支付宝红包二维码</text>
      
      <text style="color: #666;font-size: 24rpx;margin-top: 20rpx;">生成专属红包跳转页，不用扫码就能领红包，提升红包领取率</text>
      
      <a :href="config.help_page || '#'" style="color: #F56C6C;font-size: 24rpx;margin-top: 20rpx;">不会用?点这里</a>
      
      <button @click="create" style="margin-top: 50rpx;font-size: 32rpx;" type="warn">生成专属红包页面</button>
    </template>
	</view>
</template>

<script>
  import { Encoder,Decoder } from '@nuintun/qrcode';
  import lPainter from '@/uni_modules/l-painter/l-painter'
  import lPainterImage from '@/uni_modules/l-painter-image/l-painter-image'
  import lPainterText from '@/uni_modules/l-painter-text/l-painter-text'
  import lPainterView from '@/uni_modules/l-painter-view/l-painter-view'
	export default {
    components:{
    	lPainter,
    	lPainterImage,
    	lPainterText,
    	lPainterView,
    },
		data() {
			return {
        init:true,
        record:{},
        source_qrcode:[],
        indexPage:'',
        config:{},
        style:{
        		"height": 350,    // 边框高度
        		"width": 250,    // 边框宽度
        }
			}
		},
    computed:{
      page_qrcode(){
        if(this.record && this.record._id){
          const qrcode = new Encoder();
          qrcode.write(`${this.indexPage}#/pages/index?id=${this.record._id}`);
          qrcode.make();
          return qrcode.toDataURL()
        }
        return '';
      }
    },
		async onLoad({auth_code}) {
      uni.showLoading({
        mask:true,
        title:'正在加载'
      })
      let message='';
      try{
        if(window.location.search){
          this.indexPage=window.location.href.split('#')[0].replace(window.location.search,'?t=index');
        }else{
          this.indexPage=window.location.href.split('#')[0]
        }
        console.log(this.indexPage)
        const user_id= uni.getStorageSync('user_id');
        if(user_id){
          const {result:{data:[record={}]}}=await uniCloud.database().collection('alipay_redpacket').where({
            alipay_user_id:user_id,
          }).limit(1).get();
          console.log(record)
          if(record._id){
            this.record=record;
          }
        }else if(auth_code){//授权
          const {result}=await uniCloud.callFunction({
            name:'alipay_user_id',
            data:{
              code:auth_code,
            }
          })
          console.log(result)
          if(result.code ===200){
            uni.setStorageSync('user_id',result.data);
            window.location.href=`${this.indexPage}#/pages/create`
          }else{
            message=result.message;
          }
        }else{
          if(navigator.userAgent.toLowerCase().indexOf('alipay')<=-1){
            this.copy(window.location.href)
            uni.showModal({
              title:'操作提示',
              content:'链接已复制，请在支付宝客户端打开链接',
              success:()=> {
                location.href="https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=2021003154699116&scope=auth_base&state=STATE&redirect_uri="+encodeURIComponent(`${this.indexPage}`)
              }
            })
          }else{
            location.href="https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=2021003154699116&scope=auth_base&state=STATE&redirect_uri="+encodeURIComponent(`${this.indexPage}`)
          }
        }
      }finally{
        this.init=false;
        uni.hideLoading();
        if(message){
          uni.showToast({
            icon:'none',
            title:message
          })
        }
        const {result}=await uniCloud.callFunction({
          name:'alipay_config',
          data:{
          }
        })
        this.config=result.data;
      }
    },
		methods: {
      downloadPoster(){
      	uni.showLoading({
      		title:'正在保存',
      		mask:true,
      	})
      	this.$refs.painter.canvasToTempFilePathSync({
      	  fileType: "png",
      	  quality: 1,
      	  cleanTempFile:true,
      	  success: (res) => {
      	    return new Promise((resolve,reject)=>{
      	      uni.saveImageToPhotosAlbum({
      	          filePath: res.tempFilePath,
      	          success: function () {
      	      				uni.hideLoading();
      	              uni.showToast({
      	              	title:'保存相册成功'
      	              })
      	              resolve()
      	          },
      	      		fail(err){
      	      			uni.hideLoading();
      	      			console.log(err)
      	      			uni.showToast({
      	      				title:'保存相册失败'
      	      			})
      	            resolve()
      	      		}
      	      });
      	    })
      	  },
      		fail(err){
      			uni.hideLoading();
      			console.log(err)
      			uni.showToast({
      				title:'保存相册失败'
      			})
      		}
      	});
      },
      copy(text){
        uni.setClipboardData({
          data:text
        })
      },
      async create(){
        uni.showLoading({
          title:'正在创建'
        })
        let message=''
        try{
          const user_id=uni.getStorageSync('user_id');
          if(user_id){
            return message="没有获取到用户ID，请在支付宝客户端打开"
          }
          const token=await new Promise((resolve,reject)=>{
            console.log(this.source_qrcode)
            if(this.source_qrcode.length<=0 || !this.source_qrcode[0].path){
              message="没有获取到token"
              return reject('没有获取到token');
            }
            const qrcode = new Decoder();
            qrcode
              .scan(this.source_qrcode[0].path)
              .then(result => {
                let _token=result.data.substring(result.data.indexOf('19'));
                console.log('token',_token,result.data)
                resolve(_token);
              })
              .catch(error => {
                reject(error)
              });
          });
          const {result:{id}}=await uniCloud.database().collection('alipay_redpacket').add({
            alipay_user_id:user_id,
            alipay_token:token,
          })
          console.log(id)
          if(id){
            this.$set(this.record,'_id',id)
          }else{
            message="生成失败"
          }
        }catch(err){
          console.error(err)
          message=message || "生成失败"
        }finally{
          uni.hideLoading()
          if(message){
            uni.showToast({
              icon:'none',
              title:message
            })
          }
        }
      }
		}
	}
</script>

<style scoped lang="scss">
	.content{
    display: flex;
    flex-direction: column;
    align-items: center;
    background-image: linear-gradient(to bottom, #ffd08b,#ffffff,#ffffff);
    height: 100vh;
  }
  /deep/ .icon-add,.icon-add .rotate{
    background-color:#fff;
  }
</style>
